<template>
    <div class="base-page">
        <div class="left org">
            <select-org @select="onSelectOrg" />
        </div>
        <!-- 列表 -->
        <div class="right" v-if="viewList">
            <div class="e-table">
                <div class="top">
                    <div class="left">
                        <div class="left-btn">
                            <el-button type="primary"
                                @click="goAdd"
                                :disabled="!formData.orgId || tableData.length > 0"
                            >新增</el-button>
                            <span class="prompt" v-if="!formData.orgId">请先选择机构</span>
                        </div>
                    </div>
                    <div class="search_box">
                        <el-input class="ipt" type="text"
                            placeholder="输入搜索关键字"
                            v-model="searchKey"
                            @select="onSearch"
                            @change="onSearch"
                        ><img src="@/assets/search.png" slot="suffix" @click="onSearch" /></el-input>
                        <div class="adverse">
                            <el-button type="primary" size="small"
                                @click="onAdvanceSearch"
                            >高级搜索</el-button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="e-table" :style="{width: rightTableWidth}">
                <el-table
                    class="table"
                    :height="rightTableHeight"
                    :data="tableData"
                    border
                >
                    <el-table-column label="序号" type="index" width="55" fixed> </el-table-column>
                    <el-table-column prop="orgName" label="机构"
                        fixed
                        min-width="200"
                        class-name="blue-column"
                        show-overflow-tooltip
                    >
                        <template slot-scope="{ row }">
                            <span @click="onEdit(row)">{{ row.orgName }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="sporadicPurchaseQuota" label="物资零星采购限额" width="180"> </el-table-column>
                    <el-table-column prop="temporaryDemandQuota" label="周材临时需用限额" width="180"> </el-table-column>
                    <el-table-column prop="isEnable" label="启用状态" width="120">
                        <template slot-scope="{ row }">
                            {{ row.isEnable ? '是' : '否' }}
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <Pagination
                :total="paginationInfo.total"
                :pageSize.sync="paginationInfo.pageSize"
                :currentPage.sync="paginationInfo.currentPage"
                @currentChange="onCurrentChange"
                @sizeChange="onSizeChange"
            />
        </div>
        <!-- 新增、编辑界面 -->
        <div class="right" v-else>
            <div class="e-form" style="padding: 0 10px 10px;">
                <div class="tabs-title">计划限额设置</div>
                <el-form ref="form" :model="formData" label-width="150px">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="机构名称：">
                                {{ formData.orgName }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="是否启用：">
                                <el-checkbox v-model="formData.isEnable"></el-checkbox>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="物资零星采购限额：">
                                <el-input v-enterInteger1 v-model="formData.sporadicPurchaseQuota"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="周材临时需用限额：">
                                <el-input v-enterInteger1 v-model="formData.temporaryDemandQuota"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <div class="footer">
                <div class="right-btn">
                    <el-button type="primary"
                        @click="onSave"
                    >保存</el-button>
                    <el-button type="primary"
                        class="btn-delete"
                        v-if="formData.billId"
                        @click="onDel"
                    >删除</el-button>
                    <el-button
                        @click="onCancel"
                    >取消</el-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import {
    getMaterialSetList,
    addMaterialSet,
    modifyMaterialSet,
    getMaterialSet,
    delMaterialSet
} from '@/api/base/material'
import { mapMutations } from 'vuex'
import SelectOrg from '@/components/selectOrg'
import Pagination from '@/components/pagination/pagination'
import { debounce, showLoading, hideLoading, advanceSearch, selectDataClient, openAppClient } from '@/utils/common'
export default {
    components: {
        Pagination,
        SelectOrg
    },
    data () {
        return {
            viewList: true, // 显示列表还是编辑界面: true 显示列表 false 显示编辑界面
            searchKey: '',
            tableData: [],
            paginationInfo: {
                total: 0,
                pageSize: 20,
                currentPage: 1,
            },
            attachTableData: [],
            formData: {},
            currencyOptions: [],
            tabsName: 'baseInfo',
            tableData2: [],
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            idsTop: []
        }
    },
    computed: {
        // 列表宽度
        rightTableWidth () {
            return (this.screenWidth - 416) + 'px'
        },
        // 列表宽度
        rightTableHeight () {
            console.log(this.paginationInfo.total, this.screenHeight)
            return this.paginationInfo.total ? (this.screenHeight - 172) : (this.screenHeight - 120)
        },
        // tabs内表格宽度
        rightTabsWidth () {
            return (this.screenWidth - 416) + 'px'
        },
        rightTabsHeight () {
            return (this.screenHeight - 83) + 'px'
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 103 - this.lastConHeight
        },
    },
    mounted () {
        // 获取屏幕宽高
        this.getScreenInfo()
        window.addEventListener('resize', debounce(this.getScreenInfo))
    },
    methods: {
        ...mapMutations(['setSelectedInfo']),
        async getList () {
            showLoading()
            try {
                const resData = await getMaterialSetList({
                    limit: this.paginationInfo.pageSize,
                    keyword: this.searchKey,
                    orgId: this.formData.orgId,
                    page: this.paginationInfo.currentPage
                })
                hideLoading()
                this.tableData = resData.list || []
                this.paginationInfo.total = resData.totalCount
            } catch (error) {
                hideLoading()
            }
        },
        onCurrentChange () {
            this.getList()
        },
        onSizeChange () {
            this.getList()
        },
        onSelectOrg (val) {
            this.formData = {
                ...this.formData,
                ...val
            }
            this.paginationInfo.currentPage = 1
            this.getList()
        },
        onSearch (e) {
            let searchKey = e
            if (typeof e === 'object') {
                searchKey = this.searchKey
            }
            console.log(searchKey)
            this.paginationInfo.currentPage = 1
            this.getList()
        },
        goAdd () {
            console.log(this.formData, 'this.formData')
            this.formData = {
                ...this.formData,
                isEnable: false,
                sporadicPurchaseQuota: '',
                temporaryDemandQuota: ''
            }
            this.viewList = false
        },
        async onEdit ({ billId }) {
            showLoading()
            const resData = await getMaterialSet({
                id: billId
            })
            hideLoading()
            console.log(resData)
            resData.isEnable = resData.isEnable === 1
            this.formData = resData
            this.viewList = false
        },
        async onSave () {
            this.formData.isEnable = this.formData.isEnable ? 1 : 0
            this.formData.sporadicPurchaseQuota = this.formData.sporadicPurchaseQuota === '' ? 0 : Number(this.formData.sporadicPurchaseQuota)
            this.formData.temporaryDemandQuota = this.formData.temporaryDemandQuota === '' ? 0 : Number(this.formData.temporaryDemandQuota)
            showLoading()
            console.log(this.formData.billId, 'this.formData.billId')
            if (!this.formData.billId) {
                await addMaterialSet(this.formData).catch(e => {
                    console.log(e.message)
                    hideLoading()
                })
            } else {
                await modifyMaterialSet(this.formData).catch(e => {
                    console.log(e.message)
                    hideLoading()
                })
            }
            hideLoading()
            this.viewList = true
            this.paginationInfo.currentPage = 1
            this.getList()
        },
        async onDel () {
            this.clientPop('info', '确定要删除吗？数据删除后不可恢复，请谨慎操作！', async () => {
                showLoading()
                await delMaterialSet({
                    id: this.formData.billId
                }).catch(e => {
                    console.log(e.message)
                    hideLoading()
                })
                hideLoading()
                this.viewList = true
                this.getList()
            })
        },
        onCancel () {
            this.viewList = true
        },
        onSelect () {
            // 弹窗选择数据
            selectDataClient({
                SelectServiceToken: '/hr/org/getOrgByUserId', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: ['1439990097591140358'], // 已选中id
                Title: '选择机构用户' // 标题
            }).then(val => {
                // 保存用户选择返回数据到store
                this.setSelectedInfo(val)
                // 客户端弹窗预览结果
                // 参数依次为: 打开页面地址、标题、回调函数
                openAppClient('/showSelectedData', '选择结果', function () {
                    // alert('关闭后回调')
                })
            })
        },
        onAdvanceSearch () {
            advanceSearch().then(res => {
                alert(JSON.stringify(res))
            })
        },
        onChangeLoading () {
            showLoading()
            setTimeout(() => {
                hideLoading()
            }, 2000)
        },
        onCurrency () {
            this.$router.push('/baseCurrency')
        },
        onUser () {
            this.$router.push('/')
        },
        getScreenInfo () {
            let screenWidth = document.documentElement.clientWidth || document.body.clientWidth
            let screenHeight = document.documentElement.clientHeight || document.body.clientHeight
            this.screenWidth = screenWidth
            this.screenHeight = screenHeight
        }
    }
}
</script>

<style lang="scss" scoped>
</style>
